import type { MicroAppStateActions } from 'qiankun';
import { initGlobalState, registerMicroApps, start } from 'qiankun';
import { MICRO_APP_MAPPINGS } from '@/config/microAppConfig';

console.log('[Micro] micro.ts 模块已加载');

// ==================== 微应用加载状态控制 ====================

// 加载超时定时器
let loadingTimer: any = null;

/**
 * 显示微应用加载状态（Ant Design Pro 风格）
 */
function showMicroAppLoading(appName: string): void {
  console.log(`[MicroLoading] 显示加载状态: ${appName}`);
  
  // 清除之前的超时定时器
  if (loadingTimer) {
    clearTimeout(loadingTimer);
  }
  
  // 通过自定义事件通知 App.vue 显示加载效果
  window.dispatchEvent(new CustomEvent('micro-app-loading', { 
    detail: { loading: true, appName } 
  }));
  
  // 设置超时自动隐藏（10秒后）
  loadingTimer = setTimeout(() => {
    console.log(`[MicroLoading] 加载超时，自动隐藏加载状态`);
    hideMicroAppLoading();
  }, 10000);
}

/**
 * 隐藏微应用加载状态
 */
function hideMicroAppLoading(): void {
  console.log('[MicroLoading] 隐藏加载状态');
  
  // 清除超时定时器
  if (loadingTimer) {
    clearTimeout(loadingTimer);
    loadingTimer = null;
  }
  
  // 通过自定义事件通知 App.vue 隐藏加载效果
  window.dispatchEvent(new CustomEvent('micro-app-loading', { 
    detail: { loading: false } 
  }));
}

// 维护一个简单的已挂载应用名称列表，兼容旧版本 qiankun
function getMountedAppNames(): string[] {
  const arr = (window as any).__QIANKUN_MOUNTED_APPS__;
  return Array.isArray(arr) ? arr : [];
}

function addMountedApp(name: string) {
  const arr = getMountedAppNames();
  if (!arr.includes(name)) {
    (window as any).__QIANKUN_MOUNTED_APPS__ = [...arr, name];
  }
}

function removeMountedApp(name: string) {
  const arr = getMountedAppNames();
  (window as any).__QIANKUN_MOUNTED_APPS__ = arr.filter((n: string) => n !== name);
}


interface MicroAppConfig {
  name: string;
  entry: string;
  container: string;
  activeRule: string | string[] | ((location: Location) => boolean);
  props?: Record<string, any>;
}

// 兼容多种环境变量命名
function getEnvUrl(...keys: string[]): string {
  try {
    const env: any = (import.meta as any).env || {};
    for (const key of keys) {
      if (env[key]) return String(env[key]);
    }
  } catch (_) {}
  return '';
}

function normalizeEntry(url: string | undefined, fallback?: string): string {
  let u = (url || '').trim();
  if (!u && fallback) u = fallback.trim();
  if (!u) return '';
  // 支持 //localhost:3007 形式，补齐协议
  if (u.startsWith('//')) {
    u = `${window.location.protocol}${u}`;
  }
  // 去除末尾斜杠
  if (u.endsWith('/')) {
    u = u.slice(0, -1);
  }
  return u;
}

// 从配置自动生成微应用配置
const getAllMicroAppsConfig = (): MicroAppConfig[] => {
  return MICRO_APP_MAPPINGS.map(app => {
    // 如果没有配置端口或环境变量，跳过该应用
    if (!app.port || !app.envKeys) {
      console.warn(`[Micro] ${app.name} 缺少端口或环境变量配置，已跳过`);
      return null;
    }

    return {
      name: app.name,
      entry: normalizeEntry(
        getEnvUrl(...app.envKeys),
        `http://localhost:${app.port}`,
      ),
      container: '#micro-container',
      activeRule: [
        // 使用字符串形式的激活规则，更可靠
        app.prefix,
        // 备用函数形式的激活规则
        (loc: Location) => {
          const ok = loc.pathname.startsWith(app.prefix);
          console.log(`[Micro] ${app.name} 激活规则检查:`, {
            pathname: loc.pathname,
            prefix: app.prefix,
            activated: ok,
            location: loc
          });
          return ok;
        }
      ],
      props: { 
        routerBase: '/',  // 🔧 修复：使用根路径作为路由基础
        globalState, 
        messageService 
      },
    };
  }).filter(Boolean) as MicroAppConfig[];
};

// 全局状态接口
export interface GlobalState {
  user?: any;
  token?: string;
  permissions?: string[];
  roles?: string[];
  theme?: string;
  locale?: string;
  menuCollapsed?: boolean;
  activeApp?: string;
  menuList?: any[];
  layout?: string;
  isCollapse?: boolean;
  breadcrumb?: boolean;
  breadcrumbIcon?: boolean;
  tabs?: boolean;
  tabsIcon?: boolean;
  isWatermark?: boolean;
  primaryColor?: string;
}

// 创建全局状态
export let globalState: MicroAppStateActions;

// 消息服务接口
export interface MessageService {
  broadcast: (event: string, data: any) => void;
  subscribe: (event: string, callback: (data: any) => void) => void;
  unsubscribe: (event: string) => void;
}

// 创建消息服务
export const messageService: MessageService = {
  broadcast: (event, data) => {
    console.log(`[MessageService] Broadcasting event: ${event}`, data);
  },
  subscribe: (event, _callback) => {
    console.log(`[MessageService] Subscribed to event: ${event}`);
  },
  unsubscribe: (event) => {
    console.log(`[MessageService] Unsubscribed from event: ${event}`);
  },
};

/**
 * 启动 qiankun 微前端框架
 */
export function startQiankun(): Promise<void> {
  console.log('🚀 [Micro] 准备启动 qiankun 微前端框架...');
  console.log('[Micro] 环境变量探测:', {
    VITE_APP_SYSTEM_APP_URL: (import.meta as any).env?.VITE_APP_SYSTEM_APP_URL,
    VITE_SYSTEM_APP_URL: (import.meta as any).env?.VITE_SYSTEM_APP_URL,
    VITE_APP_BUSINESS_APP_URL: (import.meta as any).env?.VITE_APP_BUSINESS_APP_URL,
    VITE_BUSINESS_APP_URL: (import.meta as any).env?.VITE_BUSINESS_APP_URL,
  });

  return new Promise(async (resolve, reject) => {
    try {
      // 初始化全局状态
      try {
        globalState = initGlobalState({
          user: null,
          token: '',
          permissions: [],
          roles: [],
          theme: localStorage.getItem('theme') || 'light',
          locale: localStorage.getItem('locale') || 'zh-CN',
          menuCollapsed: false,
          activeApp: '',
          menuList: [],
          layout: 'vertical',
          isCollapse: false,
          breadcrumb: true,
          breadcrumbIcon: true,
          tabs: true,
          tabsIcon: false,
          isWatermark: true,
          primaryColor: '#1890ff', // Ant Design Pro 标准主题色（拂晓蓝）
        });

        // 监听全局状态变化
        if (globalState?.onGlobalStateChange) {
          globalState.onGlobalStateChange((state, prev) => {
            console.log('[GlobalState] 状态发生变化:', prev, '->', state);

            // 同步全局状态到 localStorage
            if (state.theme) {
              localStorage.setItem('theme', state.theme);
            }
            if (state.locale) {
              localStorage.setItem('locale', state.locale);
            }
          });
        } else {
          console.warn('[GlobalState] onGlobalStateChange API 不可用');
        }
      } catch (error) {
        console.error('[GlobalState] 初始化全局状态失败:', error);
      }

      // 获取微应用配置
      const allApps = getAllMicroAppsConfig().map((app) => ({
        ...app,
        props: {
          globalState,
          messageService,
        },
      }));

      // 筛选有效的微应用
      let apps = allApps.filter((app) => !!app.entry);
      console.log('[Micro] 准备注册微应用:', apps.map((a) => ({ name: a.name, entry: a.entry })));

      // 注册微应用
      registerMicroApps(apps, {
        beforeLoad: [
          async (app) => {
            console.log(`[Micro] 开始加载微应用: ${app.name}, entry: ${app.entry}`);
            // 显示 Ant Design Pro 风格加载效果
            showMicroAppLoading(app.name);
          },
        ],
        beforeMount: [
          async (app) => {
            console.log(`[Micro] 开始挂载微应用: ${app.name}`);
          },
        ],
        afterMount: [
          async (app) => {
            console.log(`[Micro] 微应用挂载完成: ${app.name}`);
            // 隐藏加载效果
            hideMicroAppLoading();
            // 更新全局状态中的当前激活应用
            if (globalState) {
              globalState.setGlobalState({ activeApp: app.name });
            }
            // 记录已挂载应用名称
            addMountedApp(app.name);
          },
        ],
        beforeUnmount: [
          async (app) => {
            console.log(`[Micro] 开始卸载微应用: ${app.name}`);
          },
        ],
        afterUnmount: [
          async (app) => {
            console.log(`[Micro] 微应用卸载完成: ${app.name}`);
            // 从已挂载列表中移除
            removeMountedApp(app.name);
          },
        ],
      },
      // 💡 添加错误处理
      {
        onError: (error: any) => {
          console.error('[Micro] 微应用加载失败:', error);
          // 隐藏加载状态
          hideMicroAppLoading();
        }
      } as any);

      // ✅ 启动 qiankun（增强配置）
      start({
        // ✅ 智能预加载：关闭预加载，避免不必要的请求
        prefetch: false,
        // ✅ 沙箱配置：启用 scopedCSS 防止样式穿透
        sandbox: {
          strictStyleIsolation: false,
          experimentalStyleIsolation: true, // 启用实验性样式隔离
        },
        // ✅ 允许多应用同时运行
        singular: false,
        // ✅ 自定义 fetch，添加缓存和错误处理
        fetch(url, ...args) {
          return window.fetch(url, ...args)
            .then(response => {
              if (!response.ok) {
                console.error(`[Qiankun] 获取失败: ${url}, status: ${response.status}`);
                // 加载失败时也要隐藏加载状态
                hideMicroAppLoading();
                throw new Error(`Failed to fetch: ${url}`);
              }
              return response;
            })
            .catch(error => {
              console.error(`[Qiankun] Fetch error for ${url}:`, error);
              // 加载失败时隐藏加载状态
              hideMicroAppLoading();
              throw error;
            });
        },
      });

      console.log('✅ [Micro] qiankun 微前端框架启动成功！');

      resolve();
    } catch (error: any) {
      console.error('❌ [Micro] qiankun 微前端框架启动失败:', error);
      console.error('[Micro] 错误详情:', error?.message);
      console.error('[Micro] 错误栈:', error?.stack);

      reject(error);
    }
  });
}

export default startQiankun;

/**
 * 准备就绪时启动qiankun的全局函数
 */
(window as any).startQiankunWhenReady = async function () {
  console.log('🔍 [startQiankunWhenReady] 开始检查qiankun启动条件...');

  try {
    // 检查DOM是否准备好
    if (document.readyState !== 'complete' && document.readyState !== 'interactive') {
      console.log('[startQiankunWhenReady] DOM还未完全准备好，等待DOMContentLoaded事件');
      await new Promise((resolve) => {
        if (document.readyState === 'loading') {
          document.addEventListener('DOMContentLoaded', resolve);
        } else {
          resolve(null);
        }
      });
    }

    // 检查微应用容器是否存在
    const microContainer = document.getElementById('micro-container');
    console.log('[startQiankunWhenReady] 微应用容器状态:', {
      exists: !!microContainer,
      readyState: document.readyState,
    });

    // 如果容器不存在，尝试等待一会儿再检查
    if (!microContainer) {
      console.log('[startQiankunWhenReady] 微应用容器不存在，等待500毫秒后重试...');
      await new Promise((resolve) => setTimeout(resolve, 500));

      const retryContainer = document.getElementById('micro-container');
      if (!retryContainer) {
        console.warn('[startQiankunWhenReady] 重试后容器仍不存在');
      }
    }

    // 检查是否已经启动过qiankun
    if ((window as any).isQiankunStarted) {
      console.log('[startQiankunWhenReady] qiankun框架已经启动过，跳过重复启动');
      return;
    }

    // 启动qiankun
    console.log('🚀 [startQiankunWhenReady] 准备启动qiankun框架...');
    await startQiankun();

  // 标记qiankun已启动
  (window as any).isQiankunStarted = true;
  console.log('✅ [startQiankunWhenReady] qiankun框架启动完成！');
  
  // 添加路由变化监听，确保微前端能正确激活
  setupRouteListener();
  } catch (error: any) {
    console.error('❌ [startQiankunWhenReady] qiankun启动过程中发生错误:', error);
    console.error('[startQiankunWhenReady] 错误详情:', error?.message);
    console.error('[startQiankunWhenReady] 错误栈:', error?.stack);
  }
};

/**
 * 设置路由变化监听器，确保微前端能正确激活
 */
function setupRouteListener() {
  console.log('[setupRouteListener] 设置路由变化监听器');
  
  // 只监听 popstate 事件（浏览器前进后退）
  // 不监听 pushState 和 replaceState，让 qiankun 自己处理，避免循环和页面刷新
  window.addEventListener('popstate', () => {
    console.log('[setupRouteListener] popstate 事件触发，当前路径:', window.location.pathname);
    // 延迟一下，确保路由变化完成
    setTimeout(() => {
      checkAndActivateMicroApp(window.location.pathname);
    }, 100);
  });
}

/**
 * 强制触发 qiankun 的路由重新检查
 */
function forceQiankunRouteCheck() {
  try {
    console.log('[forceQiankunRouteCheck] 强制触发 qiankun 路由检查');
    
    // 只触发一个 popstate 事件即可，不需要触发多个事件避免页面刷新
    window.dispatchEvent(new PopStateEvent('popstate', {
      state: history.state
    }));
    
    console.log('[forceQiankunRouteCheck] qiankun 路由检查已触发');
  } catch (error) {
    console.warn('[forceQiankunRouteCheck] 触发 qiankun 路由检查时出错:', error);
  }
}

// 防抖：记录最后检查的路径和时间
let lastCheckedPath: string | null = null;
let lastCheckTime: number = 0;

/**
 * 检查并激活对应的微前端应用
 */
function checkAndActivateMicroApp(pathname: string) {
  const now = Date.now();
  
  // 如果是相同路径且在500ms内，跳过检查（防止短时间内重复触发）
  if (lastCheckedPath === pathname && (now - lastCheckTime) < 500) {
    return;
  }
  
  lastCheckedPath = pathname;
  lastCheckTime = now;
  
  for (const app of MICRO_APP_MAPPINGS) {
    if (pathname.startsWith(app.prefix)) {
      // 检查当前是否有活跃的微应用（本地维护的列表）
      const mountedAppNames = getMountedAppNames();
      
      // 只在微应用未挂载时才触发激活，避免过度触发导致样式问题
      if (!mountedAppNames.includes(app.name)) {
        console.log(`[checkAndActivateMicroApp] 微应用 ${app.name} 未挂载，触发激活`);
        try {
          window.dispatchEvent(new PopStateEvent('popstate', { state: history.state }));
        } catch (_e) {}
      }
      break;
    }
  }
}


/**
 * 获取当前路径对应的微应用名称
 */
export function getCurrentMicroApp(path?: string): string | null {
  const currentPath = path || window.location.pathname;
  
  for (const app of MICRO_APP_MAPPINGS) {
    if (currentPath.startsWith(app.prefix)) {
      return app.name;
    }
  }
  
  return null;
}

/**
 * 🎯 简化的微应用重新加载函数
 */
export function forceReloadMicroApp(appName: string, delay: number = 300) {
  console.log(`[forceReloadMicroApp] 重新加载微应用: ${appName}`);
  
  setTimeout(() => {
    // 简单的重新激活：触发 popstate 事件
    window.dispatchEvent(new Event('popstate'));
    console.log(`[forceReloadMicroApp] ✅ 已触发 popstate 事件`);
  }, delay);
}

// 确保绑定到window
if (typeof window !== 'undefined' && !(window as any).startQiankunWhenReady) {
  (window as any).startQiankunWhenReady = (window as any).startQiankunWhenReady;
}

